/**
 * RDDL: Implements a random policy for a domain with a single boolean action.
 *       The action selected to be true is the first ground instance.
 * 
 * @author Scott Sanner (ssanner@gmail.com)
 * @version 10/10/10
 *
 **/

package rddl.policy;

import java.io.File;
import java.util.*;

import rddl.*;
import rddl.RDDL.PVAR_INST_DEF;
import rddl.RDDL.*;
import rddl.competition.Client;
import rddl.parser.parser;
import rddl.viz.ElevatorDisplay;
import rddl.viz.TrafficDisplay;

public class RandomBoolPolicy extends Policy {
	
	public Random _rand = new Random();
//	ElevatorDisplay disp = new ElevatorDisplay(1000);
	
	public RandomBoolPolicy () {
		
	}
	
	public RandomBoolPolicy(String instance_name) {
		super(instance_name);
	}

	public ArrayList<PVAR_INST_DEF> getActions(State s) throws EvalException {
		
		if (s == null) {
			// This should only occur on the **first step** of a POMDP trial
			// when no observations have been generated, for now, we don't
			// handle this differently since we're just choosing a random
			// action.
		}

//		disp.display(s, 0);
		System.out.println(s);
		
		// Get a map of { legal action names -> RDDL action definition }  
		Map<String,ArrayList<PVAR_INST_DEF>> action_map = 
			ActionGenerator.getLegalBoolActionMap(s);
		
		ArrayList<PVAR_INST_DEF>  act = null;
		do {
			// Return a random action selection
			ArrayList<String> actions = new ArrayList<String>(action_map.keySet());
			String action_taken = actions.get(_rand.nextInt(action_map.size()));
			
			act = action_map.get(action_taken);
			try{
				s.checkStateActionConstraints(act);
				break;
			}catch(Exception e){
				e.printStackTrace();
			}
		}while( true );
		
		System.out.println("\n--> Action taken: " + act);
		
		return act;
	}
	
	public static void main(String[] args) throws Exception {
		File f1 = new File("./rddl/job_shop_mdp.rddl");
		File f2 = new File("./rddl/job_shop_inst_6_4_3.rddl");

		DOMAIN d = parser.parse(f1)._tmDomainNodes.values().iterator().next();
		INSTANCE i = parser.parse(f2)._tmInstanceNodes.values().iterator().next();
		NONFLUENTS n = parser.parse(f2)._tmNonFluentNodes.values().iterator().next();
		
		Client cl = new Client(d, i, n, new RandomBoolPolicy(), "localhost", 2316, "random");
		
	}
}

